import { configKey } from "../utils";

import { filp, strToArray } from "../decrypt/functions";

const createKey = () => arrayToString(randArray(configKey.getKey()));

const checkKey = (yourKey: string) =>
	JSON.stringify(yourKey.split("").sort()) ===
	JSON.stringify(configKey.getKey().sort())
		? true
		: false;

const filpedKey = filp(configKey.getKey());

function arrayToString(arr: string[]): string {
	let str = "";
	arr.forEach(v => (str = str.concat(v)));
	return str;
}

function randArray(arr: string[]): string[] {
	let result: any[] = [];
	arr.forEach((v, k) => (result[k] = v));
	return result.sort(() => (Math.random() > 0.5 ? -1 : 1));
}

function encrypt(
	str: string
): {
	cipher: string;
	solution: string;
} {
	let cipher = "";
	const encryptKey: string[] = randArray(configKey.getKey());
	const solution: string = arrayToString(encryptKey);
	str.split("").forEach((_v, k) => {
		const index = (Number(filpedKey[str[k]]) + k) % configKey.getKey().length;
		cipher = cipher.concat(encryptKey[index]);
	});
	return {
		cipher,
		solution
	};
}

function encryptAs(
	str: string,
	solution: string
): {
	cipher: string;
	solution: string;
} {
	let cipher: string = "";
	const encryptKey: string[] = strToArray(solution);
	str.split("").forEach((_v, k) => {
		const index = (Number(filpedKey[str[k]]) + k) % configKey.getKey().length;
		cipher = cipher.concat(encryptKey[index]);
	});
	return {
		cipher,
		solution
	};
}

function encryptUTF8(
	str: string
): {
	cipher: string;
	solution: string;
} {
	return encrypt(encodeURI(str));
}

function encryptUTF8As(
	str: string,
	solution: string
): {
	cipher: string;
	solution: string;
} {
	return encryptAs(encodeURI(str), solution);
}
export { checkKey, createKey, encrypt, encryptUTF8, encryptAs, encryptUTF8As };
